<script setup>
import { ElMessage } from 'element-plus'
import { reactive, useTemplateRef, ref, watch } from 'vue'
import SelectDealer from './SelectDealer.vue'
import { handleLogger } from '@renderer/util/common'

const show = defineModel('show', { type: Boolean, default: false })
const emits = defineEmits(['success'])
const props = defineProps({
  editItemData: {
    type: [null, Object],
    default: null
  }
})

const levelOpts = ref([])
async function handleGetLevelOpts() {
  const res = await window.api.getAllDealerLevel()
  console.log(res)
  levelOpts.value = res
}

const formRules = {
  level: [{ required: true, message: '请选择经销商等级', trigger: 'change' }],
  name: [{ required: true, message: '请输入经销商名称', trigger: 'blur' }]
}
const formState = reactive({
  level: '',
  relation: '',
  relationName: '',
  name: '',
  address: '',
  tel: '',
  remark: ''
})
const formRef = useTemplateRef('formRef')
async function handleConfirm() {
  await formRef.value.validate()
  const parentDealerId = formState.relation || 0
  const parentDealerName = formState.relationName || ''
  let dealerLevelName = ''
  levelOpts.value.forEach((item) => {
    if (item.dealer_level_id === formState.level) {
      dealerLevelName = item.dealer_level_name
    }
  })
  let res = ''
  if (props.editItemData) {
    res = await window.api.updateDealer(
      props.editItemData.dealer_id,
      parentDealerId,
      parentDealerName,
      formState.level,
      dealerLevelName,
      formState.name,
      formState.address,
      `${formState.tel}`,
      formState.remark
    )
  } else {
    res = await window.api.insertDealer(
      parentDealerId,
      parentDealerName,
      formState.level,
      dealerLevelName,
      formState.name,
      formState.address,
      `${formState.tel}`,
      formState.remark
    )
  }
  console.log(res)
  if (res === '名称重复') {
    ElMessage.warning('经销商名称重复，请重新填写')
    return
  }
  if (res === '仅允许一条顶级经销商记录') {
    ElMessage.warning('请选择绑定关系')
    return
  }
  if (res > 0) {
    ElMessage.success(props.editItemData ? '编辑成功' : '新增成功')
    let changeStr = ''
    if (props.editItemData) {
      changeStr = `编辑经销商：${formState.name},`
      if (formState.name !== props.editItemData.dealer_name) {
        changeStr += `名称由${props.editItemData.dealer_name}改为${formState.name}；`
      }
      if (formState.level !== props.editItemData.dealer_level_id) {
        let aLevelName = ''
        levelOpts.value.forEach((item) => {
          if (item.dealer_level_id === props.editItemData.dealer_level_id) {
            aLevelName = item.dealer_level_name
          }
        })
        changeStr += `等级由${aLevelName}改为${dealerLevelName}；`
      }
      // if (parentDealerId !== props.editItemData.parent_dealer_id) {
      //   changeStr += `绑定关系由${props.editItemData.parent_dealer_name}改为${parentDealerName}`
      // }
      if (formState.tel !== props.editItemData.dealer_mobile) {
        changeStr += `电话由${props.editItemData.dealer_mobile}改为${formState.tel}；`
      }
      if (formState.address !== props.editItemData.dealer_address) {
        changeStr += `地址由${props.editItemData.dealer_address}改为${formState.address}`
      }
    } else {
      changeStr = `新增经销商：${formState.name}；等级：${dealerLevelName}；绑定关系：${parentDealerName}；电话：${formState.tel}；地址：${formState.address}`
    }
    handleLogger(changeStr)
    emits('success')
    show.value = false
  }
}

// 选择经销商
function handleRelationChange(e) {
  formState.relationName = e.dealer_name
}

watch(
  () => show.value,
  (n) => {
    if (n) {
      handleGetLevelOpts()
      if (props.editItemData) {
        formState.level = props.editItemData.dealer_level_id || ''
        formState.relation = props.editItemData.parent_dealer_id || ''
        formState.relationName = props.editItemData.parent_dealer_name || ''
        formState.name = props.editItemData.dealer_name || ''
        formState.address = props.editItemData.dealer_address || ''
        formState.tel = props.editItemData.dealer_mobile || ''
        formState.remark = props.editItemData.dealer_remark || ''
      }
    } else {
      formState.level = ''
      formState.relation = ''
      formState.relationName = ''
      formState.name = ''
      formState.address = ''
      formState.tel = ''
      formState.remark = ''
    }
  }
)
</script>

<template>
  <el-dialog
    v-model="show"
    width="500"
    :title="props.editItemData ? '编辑经销商' : '新增经销商'"
    draggable
  >
    <el-form ref="formRef" :model="formState" :rules="formRules" label-width="100px">
      <el-form-item label="经销商等级" prop="level">
        <el-select v-model="formState.level" placeholder="请选择等级">
          <el-option
            v-for="item in levelOpts"
            :key="item.dealer_level_id"
            :label="item.dealer_level_name"
            :value="item.dealer_level_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="绑定关系" prop="relation">
        <SelectDealer
          v-model:dealerid="formState.relation"
          :disabled="props.editItemData"
          @change="handleRelationChange"
        />
      </el-form-item>
      <el-form-item label="经销商名称" prop="name">
        <el-input v-model="formState.name" placeholder="请输入经销商名称"></el-input>
      </el-form-item>
      <el-form-item label="经销商地址" prop="address">
        <el-input
          v-model="formState.address"
          type="textarea"
          placeholder="请输入经销商地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="经销商电话" prop="tel">
        <el-input
          v-model.number="formState.tel"
          type="tel"
          maxlength="11"
          placeholder="请输入经销商电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formState.remark"
          type="textarea"
          placeholder="请输入备注内容"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
